/*****************************************************************************
 * Copyright (c) 2019, ..\readme.txt Technologies Inc.
 *
 * All rights reserved.
 * ****************************************************************************
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer below.
 *
 * ..\readme.txt' name may not be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ..\readme.txt "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * DISCLAIMED. IN NO EVENT SHALL ..\readme.txt BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ****************************************************************************/

/**
 * @file main.c
 * @author ..\readme.txt
 * @version v1.0.0
 *
 * @copyright Copyright (c) 2019, ..\readme.txt Technologies Inc. All rights reserved.
 */
#include <stdio.h>
#include <string.h>
#include "main.h"
#include "bme280.h"
#include "core_cm0.h"

/** @addtogroup N32G031_StdPeriph_Examples
 * @{
 */

/** @addtogroup USART_Printf
 * @{
 */

USART_InitType USART_InitStructure;
I2C_InitType I2C_InitStructure;
uint8_t txbuff[256] = {'\0'};
#define JSON_MSG "{\"msg\":\"%s\"}"
#define JSON_BME "{\"humidity\":%.1f,\"temperature\":%.1f,\"pressure\":%.3f}"

void delay_50ms(uint32_t count);
void Delay(uint32_t count);
void SysTick_Delay_Ms(__IO uint32_t ms);
int initBme280();
/**
 * @brief  Main program
 */
int main(void)
{
    RCC_ClocksType rccClocksStatus;

    /* System Clocks Configuration */
    RCC_Configuration();
    /* Configure the GPIO ports */
    GPIO_Configuration();

    RCC_GetClocksFreqValue(&rccClocksStatus);

    /* USARTy and USARTz configuration ------------------------------------------------------*/
    USART_InitStructure.BaudRate = 115200;
    USART_InitStructure.WordLength = USART_WL_8B;
    USART_InitStructure.StopBits = USART_STPB_1;
    USART_InitStructure.Parity = USART_PE_NO;
    USART_InitStructure.HardwareFlowControl = USART_HFCTRL_NONE;
    USART_InitStructure.Mode = USART_MODE_RX | USART_MODE_TX;

    /* Configure USARTx */
    USART_Init(USARTx, &USART_InitStructure);
    /* Enable the USARTx */
    USART_Enable(USARTx, ENABLE);

    // 配置I2C2
    I2C_InitStruct(&I2C_InitStructure);
    I2C_InitStructure.ClkSpeed = 100000;
    I2C_InitStructure.OwnAddr1 = 0x66 << 1;
    I2C_Init(I2C2, &I2C_InitStructure);

    I2C_Enable(I2C2, ENABLE);

    int32_t ret = initBme280();
    /* Init done */
    
    if (ret == 0) {
        sprintf((uint8_t *) txbuff, JSON_MSG, "Init done.");
    } else {
        sprintf((uint8_t *)txbuff, JSON_MSG, "Init error.");
    }

    // printf("%s", txbuff);
    // printf("\r\n");
    memset(txbuff, 0, sizeof(txbuff));

    // {
    //     RCC_ClocksType rc;
    //     RCC_GetClocksFreqValue(&rc);
    //     printf("clock:%d\r\n", rc.SysclkFreq);
    // }

    while (1) {
        sample();
        Delay(123);
    }
}

void Delay(uint32_t ms)
{
    uint32_t count = (48000 * ms);

    while (count--) {
        asm("");
    }
}

void SysTick_Delay_Ms(__IO uint32_t ms)
{
    uint32_t i;
    RCC_ClocksType RCC_Clocks;
    RCC_GetClocksFreqValue(&RCC_Clocks);
    SysTick_Config(RCC_Clocks.SysclkFreq / 1000);
    for (i = 0; i < ms; i++)
    {
        /* When the value of the counter is reduced to 0, the bit 16 of the CRTL register is set to 1.
           When set to 1, the bit  will cleared to 0 with read
        */
        while (!((SysTick->CTRL) & (1 << 16)))
            ;
    }
    // Disable SysTick timer
    SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}

int initBme280()
{
    if (BME280_Check() != BME280_SUCCESS) {
        return -1;
    }
    uint8_t id = BME280_GetVersion();
    if (id == 0) {
        return -2;
    }
    BME280_Reset();
    delay_50ms(1);
    BME280_SetFilter(BME280_FILTER_16);
    BME280_SetOSRST(BME280_OSRS_T_x2);
    BME280_SetOSRSP(BME280_OSRS_P_x16);
    BME280_SetOSRSH(BME280_OSRS_H_x1);
    BME280_Read_Calibration();

    return 0;
}
void delay_50ms(uint32_t count)
{
    uint32_t i = count;
    while (i--) {
        SysTick_Delay_Ms(50);
    }
}
void sample()
{
    BME280_SetMode(BME280_MODE_FORCED);
    Delay(10);
    int32_t ut, up, uh;
    if (BME280_Read_UTPH(&ut, &up, &uh) != BME280_SUCCESS) {
        return;
    }

    int32_t uti, upi, uhi;
    uti = BME280_CalcT(ut);
    upi = BME280_CalcP(up);
    uhi = BME280_CalcH(uh);
    sprintf(txbuff, JSON_BME, (float)uhi / 1000, (float)uti / 100, (float)(upi >> 8) / 100);
    printf("%s", txbuff);
    printf("\r\n");
    memset(txbuff, 0, sizeof(txbuff));
}
/**
 * @brief  Configures the different system clocks.
 */
void RCC_Configuration(void)
{
    /* Enable GPIO clock */
    GPIO_APBxClkCmd(USARTx_GPIO_CLK, ENABLE);
    /* Enable USARTx Clock */
    USART_APBxClkCmd(USARTx_CLK, ENABLE);
    RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_I2C2, ENABLE);
}

/**
 * @brief  Configures the different GPIO ports.
 */
void GPIO_Configuration(void)
{
    GPIO_InitType GPIO_InitStructure;

    /* Initialize GPIO_InitStructure */
    GPIO_InitStruct(&GPIO_InitStructure);

    /* Configure USARTx Tx as alternate function push-pull */
    GPIO_InitStructure.Pin = USARTx_TxPin;
    GPIO_InitStructure.GPIO_Mode = GPIO_MODE_AF_PP;
    GPIO_InitStructure.GPIO_Alternate = USARTx_Tx_GPIO_AF;
    GPIO_InitPeripheral(USARTx_GPIO, &GPIO_InitStructure);

    /* Configure USARTx Rx as alternate function push-pull */
    GPIO_InitStructure.Pin = USARTx_RxPin;
    GPIO_InitStructure.GPIO_Alternate = USARTx_Rx_GPIO_AF;
    GPIO_InitPeripheral(USARTx_GPIO, &GPIO_InitStructure);

    // i2c
    GPIO_InitStructure.Pin = GPIO_PIN_6 | GPIO_PIN_7;
    GPIO_InitStructure.GPIO_Mode = GPIO_MODE_AF_OD;
    GPIO_InitStructure.GPIO_Speed = GPIO_SPEED_HIGH;
    GPIO_InitStructure.GPIO_Pull = GPIO_NO_PULL;
    GPIO_InitStructure.GPIO_Alternate = GPIO_AF7_I2C2;
    GPIO_InitPeripheral(GPIOA, &GPIO_InitStructure);
}

/* retarget the C library printf function to the USART */
int fputc(int ch, FILE *f)
{
    USART_SendData(USARTx, (uint8_t)ch);
    while (USART_GetFlagStatus(USARTx, USART_FLAG_TXDE) == RESET)
        ;

    return (ch);
}

#ifdef USE_FULL_ASSERT

/**
 * @brief  Reports the name of the source file and the source line number
 *         where the assert_param error has occurred.
 * @param file pointer to the source file name
 * @param line assert_param error line source number
 */
void assert_failed(const uint8_t *expr, const uint8_t *file, uint32_t line)
{
    /* User can add his own implementation to report the file name and line number,
       ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
    /* Infinite loop */
    while (1)
    {
    }
}

#endif

/**
 * @}
 */

/**
 * @}
 */
